#!/usr/local/bin/python3
# encoding:utf-8
import os,sys,shutil


dir = os.path.dirname(sys.argv[0])
os.chdir(dir)
dir = os.getcwd()
print(dir)
global appdir
global dylib
global appName
appdir = ""
dylib  = ""
appName = ""
mobilepeo = ""
certificate = "iPhone Distribution: China Mobile Group Henan Co., Ltd."  #换证书后需要修改 entitlements.plist内部也需要修改

ilist = os.listdir(dir)
def getAppDir():#获取.app文件名称
  for i in ilist:
    if i.endswith(".app"):
      return i
      break
  return ""

def getDylidName():#获取动态库名称
  for i in ilist:
    if i.endswith(".dylib"):
      print(i)
      return  i
      break
  return ""
def getMobilepeoName():
  for i in ilist:
    if i.endswith(".mobileprovision"):
      return  i
      break
  return ""

def getListFiles(path):#获取app内部所以.app/.appex文件
  assert os.path.isdir(path), '%s not exist.' % path
  ret = {}
  array1 = []
  array2 = []
  array3 = []
  for root, dirs, files in os.walk(path):
    for filespath in dirs:
      ilist = os.path.splitext(filespath)
      # print (ilist)
      if ilist[1].lower().find("framework") != -1:
        array1.append("./" + os.path.join(root,filespath))
      elif ilist[1].lower().find("app") != -1:
        array2.append( "./" + os.path.join(root, filespath))
    for file in files:
      if file.find(".dylib") != -1:
        array3.append(os.path.join(root, file))

  ret["framework"] = array1
  ret["other"] = array2
  ret["dylib"] = array3

  return ret


def judgeDylib():#判断动态库是否存在
  global dylib

  if dylib == "":
    point = input("未找到动态库文件(dylib),是否继续(y/n): ")
    print('\033[1;35m')
    if point == "y":
      print("继续重签名")
      print('\033[0m')
      pass
    elif point == "n":
      print("退出重签名")
      print('\033[0m')
      sys.exit()
    else:
      print('请输入y/n')
      print('\033[0m')
      judgeDylib()



def copyForBundle():#copy文件进入.app文件
  global dylib
  global mobilepeo
  cpEmb = "cp -f %s %s" %(mobilepeo,appdir)
  # cpApp = "cp -f %s %s" %(appName,appdir)
  cpDylib = "cp -f %s %s" %(dylib,appdir)
  if dylib == "":
    pass
  else:
    os.system(cpDylib) # yty fax
    pass
  os.system(cpEmb) # yty fax
  # os.system(cpApp) # yty fax
  print('\033[1;35m')
  print(cpDylib)
  print(cpEmb)
  # print(cpApp)
  print('\033[0m')

def codesign():#重签名
  global dylib
  global appdir
  global certificate
  global appName
  sign_dylib = "codesign -f -s  '%s' %s" %(certificate,os.path.join(appdir,dylib))
  if dylib == "":
    pass
  else:
    print('\033[1;35m')
    print("动态库重签名: " + sign_dylib)
    print('\033[0m')
    os.system(sign_dylib) # yty fax
  app_paths = getListFiles(appdir)
  #.app的子文件重签名
  subFileOrDirCodeSign(".app framework 子文件重签名: ",app_paths["framework"])
  subFileOrDirCodeSign(".app dylib 子文件重签名: ",app_paths["dylib"])
  subFileOrDirCodeSign(".app other 子文件重签名: ",app_paths["other"])

  #.app文件重签名
  app_sign = "codesign -f -s '%s' --entitlements entitlements.plist %s" %(certificate,appdir)
  print('\033[1;35m')
  print("App重签名: " + app_sign)
  print('\033[0m')
  os.system(app_sign) # yty fax

def subFileOrDirCodeSign(point_str,array):
  for path in array:
    sign = "/usr/bin/codesign --force --sign '%s' %s" % (certificate, path)
    print('\033[1;35m')
    print(point_str + sign)
    print('\033[0m')
    os.system(sign)  # yty fax

def pack():#打包
  cmd = "xcrun -sdk iphoneos PackageApplication -v %s -o '%s'" %(appdir,os.path.join(dir,"%s.ipa" %appName))
  print('\033[1;35m')
  print("打包: " + cmd)
  print('\033[0m')
  os.system(cmd) # yty fax
  pass

def intoMacho():#注入动态库
  # optool install -c load -p "@executable_path/$(dylib)" -t $(AppName)
  global dylib
  global appName
  cmd = "optool install -c load -p '@executable_path/%s' -t %s.app/%s" %(dylib,appName,appName)
  # 或者  @yololib $(AppName) $(dylib)  注入
  print('\033[1;35m')
  print("注入动态库: " + cmd)
  print('\033[0m')
  os.system(cmd)
  pass


#########################

def star():#入口函数
  global dylib
  global appdir
  global certificate
  global appName
  global mobilepeo
  appdir = getAppDir()
  dylib  = getDylidName()
  mobilepeo = getMobilepeoName()
  if appdir == "" :
    print("\033[1;35m 未找到.app文件! \033[0m")
    sys.exit()
  if mobilepeo == "":
    print("\033[1;35m 未找到.mobileprovision文件 \033[0m")
    sys.exit()
  appName = os.path.splitext(appdir)[0]
  # os.system("cp -f %s %s" % (os.path.join(appdir, appName), dir))

  judgeDylib()
  if dylib == "" :
    pass
  else:
    intoMacho()
  copyForBundle()
  codesign()
  pack()



# appdir = getAppDir()
# dylib  = getDylidName()
# mobilepeo = getMobilepeoName()
# if appdir == "" :
#   print("\033[1;35m 未找到.app文件! \033[0m")
#   sys.exit()
# if mobilepeo == "":
#   print("\033[1;35m 未找到.mobileprovision文件 \033[0m")
#   sys.exit()
# appName = os.path.splitext(appdir)[0]
# os.system("cp -f %s %s" % (os.path.join(appdir, appName), dir))
# getListFiles(appdir)
star()